package com.bum.rss.service.helper;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.bum.rss.bo.SiteBO;
import com.bum.rss.exp.om.Rss;

public class FixCrawler implements ApplicationContextAware {
	SiteBO	siteBO;
	String fileName;

	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		process();
	}

	private void process() {
		String text = null;
		try {
			text = FileUtils.readFileToString(new File("crawl/" + fileName));
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (StringUtils.isBlank(text)) {
			return;
		}

		String lines[] = text.split("\n");
		for (String line : lines) {
			try {
				String url = null;
				if (line.startsWith("http://bum.vn/tin/boyvn/")) {
					System.out.println("Fix " + line);
					line = line.replace("http://bum.vn/tin/boyvn/", "");
					line = line.substring(line.indexOf("/") + 1, line.indexOf("."));

					url = "boyvn/m/" + line;
				} else if (line.startsWith("http://bum.vn/bao/bao-")) {
					System.out.println("Fix " + line);
					line = line.replace("http://bum.vn/bao/bao-", "");
					line = line.substring(line.indexOf("/") + 1, line.indexOf("."));

					url = "baomoi/m/" + line;
				}
				
				if (url != null) {
					Rss rss = siteBO.load(url, null);
					if (rss != null && rss.getEntry() != null) {
						System.out.println(rss.getEntry().getTitle());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws IOException {
		System.out.println(FileUtils.readFileToString(new File("crawl/bum-vn_20140615T103822Z_CrawlErrors.csv")));
	}

	public void setSiteBO(SiteBO siteBO) {
		this.siteBO = siteBO;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}
